package com.vhall.component.service.room.event.handler.live;

import com.alibaba.fastjson.JSONObject;
import com.vhall.component.entity.room.dto.RoomsEntityDTO;
import com.vhall.component.entity.room.enums.RoomPullStreamEnum;
import com.vhall.component.entity.room.enums.RoomStatusEnum;
import com.vhall.component.plugin.core.service.PaasService;
import com.vhall.component.service.room.RoomInnerService;
import com.vhall.component.service.room.concant.RoomConstant;
import com.vhall.component.service.room.event.handler.AbstractEventHandler;
import com.vhall.component.service.room.event.handler.EventHandlerType;
import com.vhall.component.service.room.event.handler.RedirectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

import static com.vhall.component.service.room.event.EventConstant.LIVE_PULL_STREAM_STATUS;

/**
 * 直播拉流任务开始或结束 处理器
 *
 * @author jingwen.li
 * @date 2023/2/16
 */
@Slf4j
@Component
@EventHandlerType(LIVE_PULL_STREAM_STATUS)
public class PullStreamStatusEventHandler extends AbstractEventHandler {
    @Resource
    private RoomInnerService roomInnerService;
    @Resource
    private PaasService paasService;
    @Autowired
    private RedirectUtil redirectUtil;
    @Value("${old.callback.live.url}")
    private String callbackUrl;
    @Override
    public void handle(Map<String, Object> callBack) {

//        redirectUtil.redirect(callbackUrl, callBack);

        String roomId = (String) callBack.get("room_id");
        Integer status = (Integer) callBack.get("status");
        if(Objects.equals(RoomPullStreamEnum.PULL_STREAM_ENUM.end(),status)){
            RoomsEntityDTO roomInfo = roomInnerService.getRoomInfo(roomId);
            if (Objects.nonNull(roomInfo)) {
                roomInfo.setPullStreamStatus(RoomPullStreamEnum.PULL_STREAM_ENUM.end());
                roomInfo.setStatus(RoomStatusEnum.END_BROADCAST.getStatus());
                roomInnerService.updateByIl(roomInfo);
                //====删除rtmp========
                String body = createEndLiveBody(roomInfo.getAccountId());
                //房间消息
                paasService.sendMessage(roomInfo.getChannelId(), body);
                //通知消息
                paasService.sendMessage(roomInfo.getNifyChannel(), body);
            }
        }
        log.info("收到直播拉流任务事件：{}, 事件详情：{}", LIVE_PULL_STREAM_STATUS, callBack);
    }
    private String createEndLiveBody(Integer accountId) {
        JSONObject json = new JSONObject();
        json.put("type", com.vhall.component.plugin.common.constant.RoomConstant.LIVE_OVER);
        json.put(RoomConstant.ROOM_JOIN_ID, accountId);
        return json.toJSONString();
    }
}
